import { useWebSocket } from '@vueuse/core'
import { getAccessToken } from '@/utils/auth'
import { getNowFormatDate, formatDates } from '@/utils/public'
import { useUserStore } from '@/store/modules/user'

// WebSocket连接状态管理
const websocketObj = ref(null)
const isConnected = ref(false)
const reconnectAttempts = ref(0)
const maxReconnectAttempts = 5
const reconnectInterval = ref(null)

// 用户store实例
const store = useUserStore()

/*客户头像随机 - 简化版本，只保留几个示例*/
const listIcon = ref([
  '',
  '',
  '',
  '',
  '',
  '',
  '',
  '',
  '',
  ''
])

// 构建WebSocket服务器地址
const buildServerUrl = () => {
  const token = getAccessToken()
  if (!token) {
    console.warn('客服WebSocket: 无法获取访问令牌，跳过连接')
    return null
  }

  return (
    (import.meta.env.VITE_BASE_URL + '/infra/ws').replace('http', 'ws') +
    '?userType=2&token=' +
    token
  )
}

// 创建WebSocket连接
const createWebSocketConnection = () => {
  const serverUrl = buildServerUrl()
  if (!serverUrl) {
    return null
  }

  console.log('客服WebSocket: 正在建立连接...', serverUrl)

  const { data, status, open, close } = useWebSocket(serverUrl, {
    autoReconnect: false, // 禁用自动重连，我们手动控制
    heartbeat: {
      interval: 10000
    },
    onConnected: () => {
      console.log('客服WebSocket: 连接成功')
      isConnected.value = true
      reconnectAttempts.value = 0
      clearReconnectTimer()
    },
    onDisconnected: () => {
      console.log('客服WebSocket: 连接断开')
      isConnected.value = false
      // 如果用户仍然登录，尝试重连
      if (getAccessToken() && reconnectAttempts.value < maxReconnectAttempts) {
        scheduleReconnect()
      }
    },
    onError: (error) => {
      console.error('客服WebSocket: 连接错误', error)
      isConnected.value = false
      // 如果是认证错误，不进行重连
      if (error.code === 1006 || error.code === 1011) {
        console.warn('客服WebSocket: 认证失败，停止重连')
        return
      }
      // 其他错误尝试重连
      if (getAccessToken() && reconnectAttempts.value < maxReconnectAttempts) {
        scheduleReconnect()
      }
    }
  })

  return { data, status, open, close }
}

// 清除重连定时器
const clearReconnectTimer = () => {
  if (reconnectInterval.value) {
    clearTimeout(reconnectInterval.value)
    reconnectInterval.value = null
  }
}

// 安排重连
const scheduleReconnect = () => {
  if (reconnectInterval.value) return // 已经在重连中

  reconnectAttempts.value++
  const delay = Math.min(1000 * Math.pow(2, reconnectAttempts.value - 1), 30000) // 指数退避，最大30秒

  console.log(`客服WebSocket: 将在 ${delay}ms 后进行第 ${reconnectAttempts.value} 次重连`)

  reconnectInterval.value = setTimeout(() => {
    reconnectInterval.value = null
    if (getAccessToken()) {
      connect()
    }
  }, delay)
}

// 连接WebSocket
const connect = () => {
  // 如果已经连接，先断开
  if (websocketObj.value) {
    disconnect()
  }

  // 检查是否有token
  if (!getAccessToken()) {
    console.warn('客服WebSocket: 用户未登录，无法建立连接')
    return false
  }

  // 创建新连接
  websocketObj.value = createWebSocketConnection()
  return websocketObj.value !== null
}

// 断开WebSocket连接
const disconnect = () => {
  clearReconnectTimer()

  if (websocketObj.value?.close) {
    websocketObj.value.close()
  }

  websocketObj.value = null
  isConnected.value = false
  reconnectAttempts.value = 0

  console.log('客服WebSocket: 连接已断开')
}

// 发送消息
const send = (message: string | object) => {
  if (!websocketObj.value || !isConnected.value) {
    console.warn('客服WebSocket: 连接未建立，无法发送消息')
    return false
  }

  try {
    const data = typeof message === 'string' ? message : JSON.stringify(message)
    websocketObj.value.send(data)
    return true
  } catch (error) {
    console.error('客服WebSocket: 发送消息失败', error)
    return false
  }
}

// 监听用户登录状态变化
watch(
  () => store.getIsSetUser,
  (isSetUser) => {
    if (isSetUser && getAccessToken()) {
      // 用户已登录，建立WebSocket连接
      console.log('客服WebSocket: 检测到用户登录，建立连接')
      connect()
    } else {
      // 用户未登录或登出，断开WebSocket连接
      console.log('客服WebSocket: 检测到用户登出，断开连接')
      disconnect()
    }
  },
  { immediate: true }
)

// 监听token变化
watch(
  () => getAccessToken(),
  (token) => {
    if (!token) {
      // token被清除，断开连接
      disconnect()
    } else if (store.getIsSetUser && !isConnected.value) {
      // 有新token且用户已登录但未连接，尝试连接
      connect()
    }
  }
)

// 全局监听WebSocket数据
watch(
  () => websocketObj.value?.data,
  (newValue) => {
    if (!newValue) return
    try {
      if (newValue == 'pong') {
        return
      }
      console.log(getStoreState('golbalWebcookies'), '客服全局websocket(1进入工作台)')
      if (getStoreState('golbalWebcookies') == '1') return
      const onlineCustomerList = JSON.parse(getStoreState('messageList')) || {}
      const jsonMessage = JSON.parse(newValue)
      const type = jsonMessage.type
      const content = JSON.parse(jsonMessage.content)
      if (!type) {
        ElMessage.error('未知的消息类型：' + newValue)
        return
      }
      if (type === 'service-chat-message-receive') {
        content.time = getNowFormatDate()
        content.type = 'you'
        content.reading = true
        if (Object.keys(onlineCustomerList).length && onlineCustomerList[content.fromUserKey]) {
          addMessage(content, onlineCustomerList)
        } else {
          addMyCustomerMessage(content, onlineCustomerList)
        }
      }
    } catch (e) {
      console.error('客服WebSocket消息处理错误:', e)
    }
  },
  { deep: true, immediate: true }
)

/*本地新增客户消息*/
const addMessage = (content, onlineCustomerList) => {
  const user = JSON.parse(JSON.stringify(onlineCustomerList))
  user[content.fromUserKey].push(content)
  setStoreState('messageList', JSON.stringify(user))
  store.updateNewMsg(true)
}

/*本地新增消息的客户*/
const addMyCustomerMessage = async (content, onlineCustomerList) => {
  const user = JSON.parse(JSON.stringify(onlineCustomerList))
  user[content.fromUserKey] = [content]
  setStoreState('messageList', JSON.stringify(user))
  store.updateNewMsg(true)
}

/*设置缓存*/
const setStoreState = (name, value) => {
  localStorage.setItem(name, value)
}

/*获取缓存*/
const getStoreState = (name) => {
  return localStorage.getItem(name)
}

// 页面可见性变化处理
if (typeof document !== 'undefined') {
  document.addEventListener('visibilitychange', () => {
    if (document.visibilityState === 'visible') {
      // 页面变为可见，如果用户已登录但连接断开，尝试重连
      if (getAccessToken() && store.getIsSetUser && !isConnected.value) {
        console.log('客服WebSocket: 页面重新可见，尝试重连')
        connect()
      }
    }
  })
}

// 页面卸载时清理
if (typeof window !== 'undefined') {
  window.addEventListener('beforeunload', () => {
    disconnect()
  })
}

export default {
  // WebSocket实例和数据
  websocketObj: readonly(websocketObj),
  data: computed(() => websocketObj.value?.data || ref(null)),

  // 连接状态
  isConnected: readonly(isConnected),

  // 方法
  connect,
  disconnect,
  send,

  // 状态信息
  reconnectAttempts: readonly(reconnectAttempts),
  maxReconnectAttempts,

  // 头像列表
  listIcon: listIcon
}
